<template>
    <div>
        <div class="product">
            <h2>修改物料清单</h2>
            <!-- 外层表单 -->
            <el-form :inline="true" :model="form" :rules="rulesOut" class="demo-form-inline" label-width="230px"
                style="margin:auto;width:80%;">
                <el-form-item label="产品" prop="productTmplId">
                    <el-select v-model="form.productTmplId" filterable placeholder="请选择产品" :filter-method="stockfilterMethod"
                        @change="stockidFunOut" style="width: 500px;">
                        <el-option v-for="item in stockdata" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                        <el-option style="color: blue;" label="搜索更多..." value="moreOut"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="规格参照">
                    <el-input v-model="form.validityDate" placeholder="请输入规格参照"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="库存数量" prop="productQty"> 
                    <el-input v-model="form.productQty" placeholder="请输入数量"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="productUomId">
                    <el-select v-model="form.productUomId" filterable placeholder="请选择单位" clearable   >
          <el-option v-for="item in uomList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
                   
                </el-form-item> -->
                <!-- <el-form-item label="BOM类型">
                    <el-radio v-model="form.isTax" label="t">制造此产品</el-radio>
                    <el-radio v-model="form.isTax" label="f">套件</el-radio>
                </el-form-item> -->

            </el-form>
            <!-- 订单行表格 -->
            <div class="tab">
                <div class="btn">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="addorder"
                        :disabled="flag">新增产品行</el-button>
                </div>
                <el-form :model="tableForm" ref="tableForm">
                    <el-table :data="tableForm.tableData" style="width: 90%; margin: 5px auto 30px;" border
                        :header-cell-style="{ 'text-align': 'center' }" :row-class-name="rowSysGoodsIndex"
                        :cell-style="{ 'text-align': 'center' }">
                        <el-table-column prop="sequence" label="序号" width="80">
                        </el-table-column>
                        <el-table-column prop="productTemplateId" label="产品名称" :render-header="thRequest" width="350">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.productTemplateId'"
                                    :rules="rules.productTemplateId">
                                    <el-select clear v-model="scope.row.productTemplateId" filterable placeholder="请选择产品"
                                        :filter-method="stockfilterMethod" @change="(val) => stockidFun(val, scope.$index)"
                                        class="thRed" style="width: 300px;">
                                        <el-option v-for="item in stockdata" :key="item.id" :label="item.name"
                                            :value="item.id">
                                        </el-option>
                                        <el-option style="color: blue;" label="搜索更多..." value="more"></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>

                        </el-table-column>
                        <!-- <el-table-column prop="surfaceTreatment" label="规格">
                    </el-table-column> -->
                        <el-table-column prop="productUomId" label="单位">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.productUomId" filterable placeholder="请选择单位" clearable
                                    :disabled="true">
                                    <el-option v-for="item in uomList" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="productQty" label="产品数量" :render-header="thRequest">
                            <template slot-scope="scope">
                                <el-form-item :prop="'tableData.' + scope.$index + '.productQty'" :rules="rules.productQty">
                                    <el-input class="thRed" v-model="scope.row.productQty" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="stockNum" label="库存数量">
                            <template slot-scope="scope">
                                <el-input class="borderNone" v-model="scope.row.stockNum" :disabled="true" />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="priceUnit" label="已在作业消耗">
                    </el-table-column> -->

                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-success"
                                    @click="ordersub(scope.row)">确认</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete"
                                    @click="BomDel(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
            </div>
            <!-- 提交按钮 -->
            <div class="sub">
                <!-- <el-button type="info" @click="cancelsubmit" style="width:150px" >放弃提交</el-button> -->
                <el-button type="primary" @click="submit" style="width:150px">提交</el-button>

            </div>
        </div>
       
        <!-- 产品搜索弹框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <hr>
            名称：<el-input style="width:150px;margin: 10px 10px" :clearable="true" placeholder="请输入内容" v-model="input2"
                @change="searchcp"></el-input>
            <!-- 型号：<el-input style="width:150px;margin: 30px 10px" :clearable="true" placeholder="请输入内容" v-model="input3"
                @change="searchcp"></el-input> -->
            <el-button type="primary" icon="el-icon-search" @click="searchcp">搜索</el-button>
            <el-table :data="stockListArr" @row-click="selecp">
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="规格" align="center" prop="specification" />
                <!-- <el-table-column label="内部类别" align="center" prop="categId">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.product_category" :value="scope.row.categId" />
                </template>
            </el-table-column> -->
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-dialog>
            <!--外层 产品搜索弹框 -->
            <el-dialog :title="title" :visible.sync="openOut" width="800px" append-to-body>
            <hr>
            名称：<el-input style="width:150px;margin: 10px 10px" :clearable="true" placeholder="请输入内容" v-model="input2"
                @change="searchcp"></el-input>
            <!-- 型号：<el-input style="width:150px;margin: 30px 10px" :clearable="true" placeholder="请输入内容" v-model="input3"
                @change="searchcp"></el-input> -->
            <el-button type="primary" icon="el-icon-search" @click="searchcp">搜索</el-button>
            <el-table :data="stockListArr" @row-click="selecpOut">
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="规格" align="center" prop="specification" />
                <!-- <el-table-column label="内部类别" align="center" prop="categId">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.product_category" :value="scope.row.categId" />
                </template>
            </el-table-column> -->
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-dialog>
    </div>
</template>
<script>
import { updateBom, getBom, bomAdd, bomdetail, addBom, bomedit, bomedit1, bomeditsub, delorderzz, delorderzz1, cancelsale } from '@/api/system/bom.js'
import { listStock, uom, getStock } from '@/api/system/stock.js'
import bom from "@/views/system/bom/index";
export default {
    data() {
        return {
            
            // 外层产品弹框
            openOut:false,
            // 产品弹框
            open: false,
            // 表格行下标
            tableindex: '',
            // 总条数
            total: 0,
            // 弹框产品的搜索
            input2: null,
            // 弹框的数组
            stockListArr: [],
            // 查询产品参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                sequence: null,
                description: null,
                descriptionPurchase: null,
                descriptionSale: null,
                type: null,
                categId: null,
                listPrice: null,
                volume: null,
                weight: null,
                saleOk: null,
                purchaseOk: null,
                uomId: null,
                active: null,
                color: null,
                createUid: null,
                createDate: null,
                writeUid: null,
                writeDate: null,
                specification: null,
                canBeExpensed: null,
                warehouse: null
            },
            // 新增订单行按钮禁用
            flag: false,
            // 单位数组
            uomList: [],
            // 外层表单提交验证
            rulesOut: {
                code: [
                    { required: true, message: "产品名称不能为空", trigger: ["blur", 'change'] }
                ],
                productQty: [
                    { required: true, message: '库存数量不能为空', trigger: 'blur' }
                ],
                //   productUomId: [
                //     {  required: true, message: '单位不能为空', trigger: 'blur' }
                //   ],
            },
            // 修改订单行表单参数
            form2: {},
            // 修改订单行弹框
            orderzzedit: false,
            // 总价
            amountTotal: 0,
            // 大写
            amountTotalDaxie: '零',
            // 用来存储赋值给tabledata
            mrpBomParts: [],
            // 订单行验证
            rules: {
                displayName: [
                    { required: true, message: '产品名称不能为空', trigger: 'blur' },
                ],
                productQty: [
                    { required: true, message: '产品数量不能为空', trigger: 'blur' }
                ],
                //   productUomId: [
                //     {  required: true, message: '单位不能为空', trigger: 'blur' }
                //   ],
            },
            title: '',
            // 订单行弹框
            orderzz: false,
            // 产品数组
            stockdata: [],
            // 外层表单参数
            form: {},
            // 新增订单行参数
            form1: {
                displayName: null,
                productQty: null,
                productUomId: null,
                stockNum: null,
            },
            // 表格数组
            tableForm: {
                tableData: []
            },

        };
    },
    mounted() {
        let query = this.$route.query.listId;
        this.getBomWrite(query)
        this.stockList()
        this.getUom()

    },
    methods: {
        // 点击修改物料清单跳转后请求
        getBomWrite(query) {
            getBom(query).then(res => {
                // console.log(res);
                this.form = res.data
                // 把返回的产品id查询详情并添加到产品选择框中回显
                getStock(this.form.productTmplId).then(resp => {
                // console.log(resp)
                const flag1 = this.stockdata.some((item, index) => {
                    if (item.id == this.form.productTmplId) {
                        return true   
                    }
                })
                // console.log(flag1);
                if (!flag1) {
                            this.stockdata.push(resp.data)
                        }
                // console.log(flag1);
                // this.stockdata.push(resp.data)
                // console.log(this.options);
                })
                // this.mrpBomParts = res.data.mrpBomParts
                this.tableForm.tableData = res.data.mrpBomParts
                const aa = (this.tableForm.tableData.map(item => {
                    // 把返回的产品id查询详情并添加到产品选择框中回显
                    getStock(item.productTemplateId).then(res => {
                        // console.log(res);
                        const obj = res.data
                        const flag2 = this.stockdata.some((item2, index) => {
                            if (item2.id === item.productTemplateId) {
                                return true
                            }
                        })
                        // console.log(flag1);
                        if (!flag2) {
                            this.stockdata.push(obj)
                        }

                    })
                }))
                // this.tableForm.tableData = res.data.mrpBomParts
            })
        },
        // 表格行必填*
        thRequest(h, colunm) {
            // console.log(h);
            // console.log(colunm);
            // console.log(colunm.column.label);
            return [
                h('span', { style: 'color:#f56c6c' }, '*'),
                h('span', ' ' + colunm.column.label)
            ]

        },
        /** 序号 */
        rowSysGoodsIndex({ row, rowIndex }) {
            row.sequence = rowIndex + 1;
        },
        // 放弃提交
        cancelsubmit() {
            this.$modal.confirm('是否确认放弃新增物料清单，并且清空已填写的内容').then(function () {
                return cancelsale().then({})
            }).then(() => {

                this.$modal.msgSuccess("已清除刚才所填写的内容");
                this.$router.push({
                    path: "/bom",
                    component: bom,
                    redirect: "noRedirect",
                    hidden: false,
                    alwaysShow: true,
                });
            }).catch((err) => {
                // console.log(err);
            });
        },
        // 物料清单提交
        submit() {
            // console.log(this.form);
            const aa = this.form
            this.$modal.confirm('是否确认修改物料清单').then(function () {
                return updateBom(aa).then({})
            }).then(() => {
                // this.getList();
                // this.getStkBomPart(stockid)
                this.$modal.msgSuccess("修改成功");
                this.$router.push({
                    path: "/bom",
                    component: bom,
                    redirect: "noRedirect",
                    hidden: false,
                    alwaysShow: true,
                });
            }).catch((err) => {
                // console.log(err);
                this.$message("修改失败");
            });
        },
        // 清空订单行参数
        reset() {
            this.form1 = {
                displayName: null,
                productQty: null,
                productUomId: null,
                stockNum: null,
            }
        },
        /** 查询库存列表 */
        getList() {
            // this.loading = true;
            this.queryParams.params = {};
            if (null != this.daterangeCreateDate && '' != this.daterangeCreateDate) {
                this.queryParams.params["beginCreateDate"] = this.daterangeCreateDate[0];
                this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
            }
            if (null != this.daterangeWriteDate && '' != this.daterangeWriteDate) {
                this.queryParams.params["beginWriteDate"] = this.daterangeWriteDate[0];
                this.queryParams.params["endWriteDate"] = this.daterangeWriteDate[1];
            }
            listStock(this.queryParams).then(response => {
                this.stockListArr = response.rows;
                this.total = response.total;
                this.stockdata = response.rows
                this.loading = false;
            });
        },

        // 获取单位
        getUom() {
            uom().then(res => {
                // console.log(res);
                this.uomList = res.data
            })
        },
        // 外层选择产品赋值
        stockidFunOut(e) {
            // console.log(e);
            if (e == 'moreOut') {
                this.openOut = true
                this.title = '搜索：产品'
                // this.tableindex = index
                this.getList()
            } else {
                this.form.productTmplId = e
 
            }
            
        },
        // 订单行选择产品赋值
        stockidFun(e, index) {
            // console.log(e);
            // console.log(e);
            if (e == 'more') {
                // console.log('123');
                this.open = true
                this.title = '搜索：产品'
                this.tableForm.tableData[index].productTemplateId = ''
                this.tableindex = index
                this.getList()
            } else {
                bomdetail(e).then(res => {
                    // console.log(res);
                    const arr = this.tableForm.tableData.map(item => {
                        // return item.sequence==this.tableForm.tableData.length
                        if (item.sequence === this.tableForm.tableData.length) {
                            item.productId = res.data[0].productId
                            item.displayName = res.data[0].displayName
                            item.productQty = res.data[0].productQty
                            item.productUomId = res.data[0].productUomId
                            item.stockNum = res.data[0].stockNum

                        }
                    })
                })
            }
        },
        // 在弹框选中产品回写到产品行
        selecp(row) {          
                // console.log(this.tableindex);
            this.tableForm.tableData[this.tableindex].productTemplateId = row.id
            this.open = false
            this.stockidFun(row.id)
          
        },
         // 外层产品在弹框选中回写下拉框
         selecpOut(row) {
            this.form.productTmplId = row.id
            this.openOut=false
        },
         // 产品弹框的搜索
         searchcp() {
            const que = {
                pageNum: 1,
                pageSize: 10,
                name: this.input2,
                // stockType: this.input3
            }
            listStock(que).then(response => {
                console.log(response);
                this.stockListArr = response.rows;
                // this.total = response.total;

                // this.loading = false;
            });
        },
        // 下拉框选择产品组件,用于下拉框显示默认十条
        stockList() {
            listStock(this.stockquery).then(res => {
                // console.log(res);
                this.stockdata = res.rows
                // console.log(this.stockdata);

            })
        },
       
        // 产品搜索，用于直接在下拉框搜索
        stockfilterMethod(node, val) {
            // console.log(node, val);
            const que = {
                name: node,
                pageSize: 100
            }
            // console.log(que);
            listStock(que).then(res => {
                // console.log(res);
                this.stockdata = res.rows
            })
        },
        // 新增订单行按钮
        addorder() {
            this.flag = true
            // this.orderzz = true
            // this.reset()
            let obj = {};
            obj.productTemplateId = "";
            obj.productUomId = "";
            obj.productQty = "";

            // console.log(this.tableForm.tableData);
            if (this.tableForm.tableData === null) {
                this.tableForm.tableData = []
            }
            this.tableForm.tableData.push(obj);
        },
        // 取消按钮
        cancel() {
            this.orderzz = false;
            this.orderzzedit = false;
            // this.Bomadd = false;
            //   this.reset();
        },
        ordersub(row) {
            // console.log(this.tableForm);
            this.$refs["tableForm"].validate((valid) => {
                // console.log(valid);
                if (valid) {
                    this.flag = false
                    const id = row.sequence - 1
                    // console.log(id);
                    // console.log(this.tableForm.tableData);
                    // const arr = []
                    // arr.push(this.tableForm.tableData[id])
                    this.form.mrpBomParts = this.tableForm.tableData
                    // console.log(this.form);
                    bomAdd(this.form).then(res => {
                        // console.log(res);
                        this.form = res.data
                        this.tableForm.tableData = res.data.mrpBomParts
                        // this.amountTotalDaxie = res.data.amountTotalDaxie
                        // this.amountTotal = res.data.amountTotal

                    })
                }
            })
        },
        // 订单行新增提交
        orderForm() {
            this.$refs["form1"].validate(valid => {
                if (valid) {
                    // console.log(this.mrpBomParts);
                    // console.log(this.form1);
                    // console.log(this.form);
                    if (this.mrpBomParts === null || this.mrpBomParts === undefined) { this.mrpBomParts = [] }
                    // this.mrpBomParts=[]
                    this.mrpBomParts.push(this.form1)
                    this.form.mrpBomParts = this.mrpBomParts
                    // console.log(this.mrpBomParts);
                    // console.log(this.form);
                    bomAdd(this.form).then(res => {
                        // console.log(res);
                        this.orderzz = false
                        this.tableForm.tableData = res.data.mrpBomParts
                        this.form = res.data

                    })
                }
            });
        },
        // 订单行删除
        BomDel(row) {
            const that = this
            // console.log(row);
            const id = row.sequence
            // this.delorder(id)
            this.$modal.confirm('是否确认删除产品名称为"' + row.displayName + '"的数据项？').then(function () {
                return that.delorder(id)
            }).then(() => {
                // this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch((err) => {
                // console.log(err);
            });

        },
        // 订单行删除接口方法
        delorder(id) {
            if (this.flag === true) {
                this.tableForm.tableData.pop()
                this.flag = false

            } else {
                // console.log(id);
                delorderzz1(id).then(res => {
                    // console.log(res);
                    // console.log(this.mrpBomParts);
                    this.mrpBomParts = res.data.mrpBomParts
                    this.form = res.data
                    // console.log(this.form);
                    // console.log(this.form.deliveryConditionsId);
                    this.tableForm.tableData = res.data.mrpBomParts


                })
            }
        },
        // 修改订单行
        orderUpdate(row) {
            const id = row.sequence
            this.orderzzedit = true
            bomedit1(id).then(res => {
                // console.log(res);
                this.title = '修改订单行'
                this.form2 = res.data

            })
        },
        // 修改订单行提交
        editsubBomForm() {
            // console.log(this.form2);
            bomeditsub(this.form2).then(res => {
                // console.log(res);
                this.mrpBomParts = res.data.mrpBomParts
                this.form = res.data
                this.tableForm.tableData = res.data.mrpBomParts
                this.orderzzedit = false
            })
        },
    },
    components: {},
    props: {},
    watch: {},
    computed: {},
    created() { },
};
</script>
<style lang="scss" scoped>
.product {
    width: 80%;
    background: #fff;
    border: 1px rgb(232, 228, 228) solid;
    // box-shadow: 0 3px 20px -15px #000000;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 10px auto;
}

h2 {
    text-align: center;
    line-height: 60px;
}

.btn {
    margin-left: 5%;
}

.sub {
    // width: 80%;
    // border: 1px red solid;
    text-align: center;
    margin-bottom: 20px;

}

.total {

    // border: 1px red solid;
    width: 90%;
    margin: 50px auto;

    // margin: 40px 60% 30px;
    // border-top: 2px gray solid;
    // text-align:right;
    .totalright {
        width: 30%;
        // float: right;
        margin-left: 70%;
        border-top: 2px gray solid;

        p {
            line-height: 40px;
            text-align: right;
        }
    }

}

.thRed {
    // height: 200px;
    margin-top: 22px;
}
</style>